package com.hyou.starter.autoconfigure.datasource.tomcat;

import javax.sql.DataSource;

import org.apache.tomcat.jdbc.pool.PoolConfiguration;
import org.apache.tomcat.jdbc.pool.PoolProperties;

/**
 * Tomcat数据源构造工具
 * 
 * @author FengChangshuo
 * @version 1.0.0 2018-03-21 17:28:11 初始创建
 */
public class TomcatDataSourceUtil {
    
    private TomcatDataSourceUtil() {
        
    }
    
    /**
     * 构造Tomcat数据源实例
     * 
     * @param dataSourceProp 数据源配置参数
     * @return 数据源对象
     */
    public static DataSource makeDataSource(TomcatDataSourceProp dataSourceProp) {
        org.apache.tomcat.jdbc.pool.DataSource dataSource = new org.apache.tomcat.jdbc.pool.DataSource();
        
        PoolConfiguration poolProperties = new PoolProperties();
        poolProperties.setDriverClassName(dataSourceProp.getDriverClassName());
        poolProperties.setUrl(dataSourceProp.getUrl());
        poolProperties.setUsername(dataSourceProp.getUsername());
        poolProperties.setPassword(dataSourceProp.getPassword());
        poolProperties.setJmxEnabled(dataSourceProp.isJmxEnabled());
        poolProperties.setTestWhileIdle(dataSourceProp.isTestWhileIdle());
        poolProperties.setTestOnBorrow(dataSourceProp.isTestOnBorrow());
        poolProperties.setTestOnReturn(dataSourceProp.isTestOnReturn());
        poolProperties.setValidationInterval(dataSourceProp.getValidationInterval());
        poolProperties.setValidationQuery(dataSourceProp.getValidationQuery());
        poolProperties.setTimeBetweenEvictionRunsMillis(dataSourceProp.getTimeBetweenEvictionRunsMillis());
        poolProperties.setMaxActive(dataSourceProp.getMaxActive());
        poolProperties.setInitialSize(dataSourceProp.getInitialSize());
        poolProperties.setMaxWait(dataSourceProp.getMaxWait());
        poolProperties.setRemoveAbandoned(dataSourceProp.isRemoveAbandoned());
        poolProperties.setRemoveAbandonedTimeout(dataSourceProp.getRemoveAbandonedTimeout());
        poolProperties.setMinEvictableIdleTimeMillis(dataSourceProp.getMinEvictableIdleTimeMillis());
        poolProperties.setMinIdle(dataSourceProp.getMinIdle());
        poolProperties.setLogAbandoned(dataSourceProp.isLogAbandoned());
        
        String jdbcInterceptors = "org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"
                + "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer";
        poolProperties.setJdbcInterceptors(jdbcInterceptors);
        
        dataSource.setPoolProperties(poolProperties);
        return dataSource;
    }
    
}
